'use strict';
import * as glu from "./utils/glutils.js";
import Main from "./pages/main.js";

const canvas = document.createElement("canvas");
const dpr = window.devicePixelRatio;
canvas.height = window.screen.height * dpr;
canvas.width = window.screen.width * dpr;
canvas.onclick = (e) => {
  canvas.requestFullscreen();
  if (canvas.onmyclick)
    canvas.onmyclick(e);
};
document.body.append(canvas);
window.gl = canvas.getContext("webgl");
const eye = mat4.create();
window.ch = window.screen.height*0.5, window.cw = window.screen.width*0.5;
let ves, offloc, mvp0, mvp1;

gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.2, 0.2, 0.2, 1.0);
gl.lineWidth(dpr*2);
initGL();
Main.getInstance();

function initGL() {
  // 创建shader
  const vs_shader = glu.loadShader(gl, gl.VERTEX_SHADER, glu.vs_source);
  const fs_shader = glu.loadShader(gl, gl.FRAGMENT_SHADER, glu.fs_source);
  // 创建program
  const program = gl.createProgram();
  gl.attachShader(program, vs_shader);
  gl.attachShader(program, fs_shader);
  gl.linkProgram(program);
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    const error = gl.getProgramInfoLog(program);
    console.log('无法链接程序对象：' + error);
    gl.deleteProgram(program);
    gl.deleteShader(fs_shader);
    gl.deleteShader(vs_shader);
    return;
  }
  gl.useProgram(program);
  gl.program = program;
  // 获取着色器变量位置和赋值
  gl.a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if (gl.a_Position < 0) {
    console.log('Failed to get the storage location of a_Position');
    return;
  }

  const texloc = gl.getAttribLocation(gl.program, 'aTex');
  const SIZE = Float32Array.BYTES_PER_ELEMENT;
  const vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.vertexAttribPointer(gl.a_Position, 2, gl.FLOAT, false, SIZE * 4, 0);
  gl.vertexAttribPointer(texloc, 2, gl.FLOAT, false, SIZE*4, SIZE*2);
  gl.enableVertexAttribArray(gl.a_Position);
  gl.enableVertexAttribArray(texloc);
  gl.texloc = texloc;
  gl.colorloc = gl.getUniformLocation(gl.program, 'isColor');
  gl.uniform1i(gl.colorloc, 0);
  mvp0 = mat4.create();
  gl.eye = mvp0;
  gl.mvploc = gl.getUniformLocation(gl.program, "u_mvp");
  gl.uniformMatrix4fv(gl.mvploc, false, mvp0);
  const aPointSize = gl.getUniformLocation(gl.program, 'a_PointSize');
  gl.uniform1f(aPointSize, 12*dpr);
  const uProj = gl.getUniformLocation(gl.program, 'u_proj');
  const projMat = mat4.create();
  mat4.ortho(projMat, 0, window.screen.width, window.screen.height, 0, -1.0, 1.0);
  gl.uniformMatrix4fv(uProj, false, projMat);
  gl.enable(gl.BLEND);
  gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
}